export const getCurrentUrl = () => {
  return new Promise<string>((resolve, reject) => {
    chrome.tabs.query(
      {
        active: true,
        currentWindow: true,
      },
      ([tab]) => {
        if (!tab) {
          return reject(new Error("请选择窗口"));
        }
        resolve(tab.url!);
      }
    );
  });
};

export const comonHandlers: Record<string, (...args: any[]) => Promise<any>> = {
  async reload() {
    chrome.runtime.reload();
  },
  async fetch(...[url, options]: Parameters<typeof fetch>) {
    const res = await fetch(url, options);
    return {
      headers: [...res.headers.entries()],
      body: await res.text(),
      status: res.status,
    };
  },
  excuteScript(code: string) {
    return new Promise((resolve) => {
      chrome.tabs.executeScript(
        {
          code,
        },
        (result) => resolve(result && result[0])
      );
    });
  },
  /**
   * 隐身模式下执行
   * @param data
   * @param url
   */
  excuteScriptAtIncognito(data: string) {
    return new Promise<void>((resolve) => {
      const url =
        "mid.html?" +
        new URLSearchParams({
          code: JSON.stringify({
            type: "excuteScript",
            data,
          }),
        }).toString();
      if (chrome.extension.inIncognitoContext) {
        window.open(url);
        return;
      }
      chrome.storage.sync.set(
        {
          openPageInIncognito: url,
        },
        () => {
          resolve();
        }
      );
    });
  },
  async getCookie(name: string, url?: string) {
    if (!url) {
      url = await getCurrentUrl();
    }
    return new Promise((resolve) => {
      chrome.cookies.get(
        {
          name,
          url: url!,
        },
        resolve
      );
    });
  },
  async setCookie(data: {
    name: string;
    value: string;
    url?: string;
    domain?: string;
  }) {
    let { url } = data;
    if (!url) {
      url = await getCurrentUrl();
    }
    return new Promise((resolve) => {
      chrome.cookies.set(
        {
          ...data,
          url: url!,
        },
        resolve
      );
    });
  },
  getCurrentUrl,
  reloadCurrentTab() {
    return new Promise<void>((resolve) => {
      chrome.tabs.reload(resolve);
    });
  },
  /**
   * 将当前tab更新为指定的url
   * @param url 
   * @returns 
   */
  goto(url: string) {
    return new Promise((resolve) => {
      chrome.tabs.update(
        {
          active: true,
          url,
        },
        resolve
      );
    });
  },
  getExtensionInfo() {
    return {
      // @ts-ignore
      ...(chrome.app ? chrome.app.getDetails() : null),
      id: chrome.runtime?.id,
      url: location.href,
    };
  },
  async openPage(url: string, target = "_blank") {
    window.open(url, target);
  },
  getStorage(names: string[]) {
    return new Promise<Record<string, any>>((resolve) => {
      chrome.storage.sync.get(names, resolve);
    });
  },
  setStorage(data: Record<string, any>) {
    return new Promise<void>((resolve) => {
      chrome.storage.sync.set(data, resolve);
    });
  },
};
